package com.cube.dp.cor.filter;

import com.cube.dp.cor.common.TransformErrorCode;
import com.cube.dp.cor.common.TransformException;
import com.cube.dp.cor.context.TransformContext;
import com.cube.dp.cor.context.TransformStatus;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cube.li
 * @date 2021/12/13 21:37
 * <p>
 * 短链映射过滤器,将短链转换为原始长链
 */
@Component
@Slf4j
public class UrlMappingTransformFilter implements TransformFilter {

    /**
     * 短链与原始链接的映射,实际项目中应该从数据库中查找
     */
    private static final Map<String, String> SHORT_URL_MAP = new HashMap<>();

    static {
        SHORT_URL_MAP.put("1deN4", "https://www.jianshu.com/u/94fe913745b7");
        SHORT_URL_MAP.put("jji3N", "https://www.zhihu.com/question/315448681");
    }

    @Override
    public void doFilter(TransformContext context) {
        log.debug("转换转换过滤器...");
        if (SHORT_URL_MAP.containsKey(context.getShortUrlCode())) {
            //找到对应的长链
            context.setOriginLongUrl(getOriginUrl(context.getShortUrlCode()));
            context.setTransformStatus(TransformStatus.TRANSFORM_SUCCESS);
        } else {
            context.setTransformStatus(TransformStatus.TRANSFORM_FAIL);
            throw new TransformException(TransformErrorCode.INVALID_ST);
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }

    /**
     * 获取原始链接
     *
     * @param shortUrl 短链
     * @return 原始链接
     */
    @NonNull
    private String getOriginUrl(String shortUrl) {
        return SHORT_URL_MAP.get(shortUrl);
    }
}
